//
//  GKVideoCaptureController.m
//  视频采集
//
//  Created by Apple on 16/11/1.
//  Copyright © 2016年 郭凯. All rights reserved.
//
#define MaxTime   8

#import "GKVideoCaptureController.h"
#import <CoreMotion/CoreMotion.h>
#import "GKVideoCammer.h"

@interface GKVideoCaptureController ()<GKVideoCammerDelegate>
/**闪关灯开关*/
@property (weak, nonatomic) IBOutlet UIButton *flashLightBT;
/**切换摄像头开关*/
@property (weak, nonatomic) IBOutlet UIButton *changeCameraBT;
/**删除按钮*/
@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;
/**录制按钮*/
@property (weak, nonatomic) IBOutlet UIButton *recordBt;
/**完成录制按钮*/
@property (weak, nonatomic) IBOutlet UIButton *finishVideoBT;
/**导航栏顶部约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewTop;
/**视频预览图层*/
@property (strong, nonatomic) IBOutlet GPUImageView *videoPreview;
/**美颜按钮*/
@property (strong, nonatomic) IBOutlet UIButton *beautiBtn;
/**进度条*/
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/**陀螺仪加速器*/
@property (nonatomic, strong) CMMotionManager * motionManager;
/**设备监视器*/
@property (nonatomic,strong)  CMDeviceMotion* deviceMotion;
/**自定义采集相机*/
@property (nonatomic,strong) GKVideoCammer* videoCammer;
@end

@implementation GKVideoCaptureController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startMotionManager];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.motionManager stopDeviceMotionUpdates];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
        NSLog(@"我走了");
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"我来了");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addAnimationForRecordViewsShow:NO];
    /**初始化自定义相机*/
    self.videoCammer = [[GKVideoCammer alloc]initWithPreview:self.videoPreview];
    self.videoCammer.delegate = self;
    __weak typeof(self) weakself = self;
    [self.videoCammer setVideoRecordProgress:^(CGFloat progress) {
        weakself.progressView.progress = progress;
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(EnterBackgroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
}
/**开始陀螺仪检测*/
- (void)startMotionManager{
    if (_motionManager == nil) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    _motionManager.deviceMotionUpdateInterval = 1;//每一秒监视一次
    if (_motionManager.deviceMotionAvailable) {
        NSLog(@"设备陀螺仪可用");
        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler: ^(CMDeviceMotion *motion, NSError *error){
            [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
        }];
    } else {
        NSLog(@"设备陀螺仪不可用");
        [self setMotionManager:nil];
    }
}

- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
    self.deviceMotion = deviceMotion;
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x)){
        if (y >= 0){//平躺垂直朝上,home键在上
            [self setUpRotation:M_PI];
        }else{//垂直向上,home键在下
            [self setUpRotation:0];
        }
    }else{
        if (x >= 0){//向右旋转
            [self setUpRotation:-M_PI_2];
        }else{//向左旋转
            [self setUpRotation:M_PI_2];
        }
    }
}

// 设置录制方向和录制的分辨率
-(CGFloat )getRecordDriection{
    if (!self.motionManager.deviceMotionAvailable) {//如果陀螺仪设备不可用
        return 0;
    }
    double x = _deviceMotion.gravity.x;
    double y = _deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x)){
        if (y >= 0){//平躺垂直朝下,Home键在上
            //设置视频录制的方向
            return M_PI;
        }else{//垂直向上,Home键在下
            //设置视频录制的方向
            return 0;
        }
    }else{
        if (x >= 0){//向右旋转,Home键在左
            //设置视频录制的方向
            return M_PI_2;
        }else{//向左旋转,Home键在右
            return -M_PI_2;
        }
    }
}

// 显示或者隐藏recordView Btn
-(void)addAnimationForRecordViewsShow:(BOOL)show{
    self.finishVideoBT.hidden =!show;;
    self.deleteBtn.hidden =!show;
}

// 设置控件的旋转方向
-(void)setUpRotation:(CGFloat)angle{
    CGAffineTransform trans = CGAffineTransformMakeRotation(0);
    [UIView animateWithDuration:0.25 animations:^{
        self.deleteBtn.transform =CGAffineTransformRotate(trans, angle);
        self.finishVideoBT.transform =CGAffineTransformRotate(trans, angle);
    }];
}

//进入后台
-(void)EnterBackgroundNotification{
    if (self.videoCammer.isfinishRecording) return;
    [self cancelRecording];
    self.flashLightBT.selected = NO;
}

#pragma mark - 各种点击事件
//返回点击事件
- (IBAction)dismissAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//开关闪光灯
- (IBAction)flashLightAction:(UIButton *)sender {
    if (self.videoCammer.cameraPosition!= GKcamerapPositionBack)  return;
     sender.selected = !sender.selected;
    if (sender.selected) {//开启闪关灯
        [self.videoCammer openFlash];
    }else{//关闭闪关灯
        [self.videoCammer closeFlash];
    }
}

//切换前后摄像头
- (IBAction)changeCameraAction:(id)sender {
    [self.videoCammer rotateCamera];
    self.flashLightBT.selected = NO;
 }
/**切换美颜*/
- (IBAction)beautityBtn:(id)sender {
    self.beautiBtn.selected = !self.beautiBtn.selected;
    if (!self.beautiBtn.selected) {
        [self.videoCammer closeBeauty];
    }
    else {
        [self.videoCammer openBeauty];
    }
}

//点击上传视频
- (IBAction)locationVideoAction:(id)sender {
    self.recordBt.selected = NO;
    [self adjustViewFrame];
    [self.videoCammer finishedVideoRecord];
    [self.navigationController popViewControllerAnimated:YES];
}

//开始和暂停录制事件
- (IBAction)recordAction:(UIButton *)sender {
    [self addAnimationForRecordViewsShow:YES];
    if (!self.recordBt.selected){
        if (!self.videoCammer.isRecording&&!self.videoCammer.isfinishRecording) {
            CGFloat angle = [self getRecordDriection];//开始录制
            [self.videoCammer startRecordWithCammerAngle:angle beauty:self.beautiBtn.selected];
        }else{
            if (self.videoCammer.isfinishRecording) return;
              [self.videoCammer resumeRecord];//恢复录制
        }
     }else{
            if (self.videoCammer.isfinishRecording) return;
            [self.videoCammer pasueRecord];//暂停录制
    }
    self.recordBt.selected = !self.recordBt.selected;
    [self adjustViewFrame];
  }


//根据状态调整view的展示情况
- (void)adjustViewFrame {
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        if (self.recordBt.selected) {
            self.topViewTop.constant = -64;
            [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
        }else {
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
            self.topViewTop.constant = 0;
        }
        [self.view layoutIfNeeded];
    } completion:nil];
}

//删除录制的视频
- (IBAction)deleteRecordVideo:(id)sender {
    [self cancelRecording];
}

// 取消录制
-(void)cancelRecording{
    [self.videoCammer cancelRecord];
    self.recordBt.selected = NO;
    self.progressView.progress = 0;
    [self adjustViewFrame];
}

#pragma mark 代理方法
-(void)videoRecordFinished{
    NSLog(@"录制完成");
    self.recordBt.selected = NO;
    self.flashLightBT.selected = NO;
    
    [self adjustViewFrame];
}



- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


- (void)dealloc {
    NSLog(@"%s",__FUNCTION__);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
